<template>
  <div>
    <el-card shadow="always">
      <el-table :data="cateList" style="width: 100%" :row-key="madeRowKey" border lazy :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="id" label="分类ID" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column label="操作">
          <template #header>
            <el-input placeholder="按Enter添加一级分类"></el-input>
          </template>
          <template #default="{ row }">
            <el-button :disabled="!!row.category2Id" type="primary" :icon="Plus" size="small"></el-button>
            <el-button type="primary" :icon="Edit" size="small"></el-button>
            <el-button type="danger" :icon="Delete" size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {

}
</script>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { reqGetCategory1, reqGetCategory2, reqGetCategory3 } from '@/api/product/category'
const load = async (row, treeNode, resolve) => {
  let res
  // 如果存在一级分类，则点击的为二级分类，则要请求对应的三级分类
  if (row.category1Id) {
    res = await reqGetCategory3(row.id)
  } else {
    res = await reqGetCategory2(row.id)
    res = res.map(item => {
      item.hasChildren = true
      return item
    })
  }
  resolve(res)
}
const cateList = ref([])

// 获取一级分类
const getCate1 = async () => {
  const res = await reqGetCategory1()
  cateList.value = res.map(item => { item.hasChildren = true; return item })
}
onMounted(() => {
  getCate1()
})

// 动态生成 table 的 row-key
const madeRowKey = (row) => {
  return row.id + row.name
}

</script>
<style>

</style>